import { getItem, setItem } from '@/utils/storage'
import store from '../index'
import type { MenuListItem } from '@/store/type/baseInfo'
import type { FuncState } from '@/store/type/func'

export default {
  namespaced: true,
  state: () => ({
    routeTags: getItem('routeTags') || [] // 路由标签
  }),
  getters: {},
  mutations: {
    addTags (state: FuncState, payload: string) {
      const result = state.routeTags.find((item) => item.path === payload)
      if (result) return
      const menuList = store.state.baseInfo.menuList
      let currentMenu: null | MenuListItem = null
      menuList.find((item) => dgLookAt(item))
      function dgLookAt (obj: MenuListItem): boolean {
        if (obj.path === payload) {
          currentMenu = obj
          return true
        }
        if (obj.children && obj.children.length > 0) {
          const result = obj.children.find((item) => dgLookAt(item))
          return !!result
        }
        return false
      }
      if (!currentMenu) return
      state.routeTags.push(currentMenu)
      setItem('routeTags', state.routeTags)
    },
    delTag (state: FuncState, payload: string) {
      const routeTags = state.routeTags.filter((item) => item.path !== payload)
      state.routeTags = routeTags
      setItem('routeTags', routeTags)
    },
    filterTag (state: FuncState, payload: { path: string; direction: string }) {
      let routeTags = state.routeTags
      if (routeTags.length < 2) return
      const firstTag = routeTags[0]
      const index = routeTags.findIndex((item) => item.path === payload.path)
      routeTags = routeTags.filter((item, index1) => {
        switch (payload.direction) {
          case 'right':
            return index1 < index + 1
          case 'left':
            return index1 > index - 1
          case 'all':
            return item.path === firstTag.path
          case 'other':
            return item.path === routeTags[index].path
          default:
            return true
        }
      })
      if (routeTags[0].path !== firstTag.path) routeTags.unshift(firstTag)
      state.routeTags = routeTags
      setItem('routeTags', routeTags)
    }
  },
  actions: {}
}
